<template>
  <!-- !项目内容 -->
  <div class="village-info">
    <section class="header">
      <a-page-header style="padding: 10px 16px 0 16px" :backIcon="false">
        <template #title>
          <a-space>
            <BlIcon type="tree-xiangmu" />
            <span>{{ villageDetail.name }}</span>
          </a-space>
        </template>
        <template #extra>
          <a-space>
            <a-button
              v-permission="['villageList', 'curd', 'delete']"
              danger
              @click="onVillageRemove"
            >
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
            <a-button
              v-permission="['villageList', 'curd', 'edit']"
              type="primary"
              ghost
              @click="onVillageEdit"
            >
              <template #icon>
                <FormOutlined />
              </template>
              编辑
            </a-button>
          </a-space>
        </template>
      </a-page-header>
      <a-menu
        mode="horizontal"
        :selectedKeys="[currentMenu.id]"
        @select="onMenuSelect"
      >
        <a-menu-item v-for="item of menuList" :key="item.id">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </section>
    <section class="content">
      <template v-if="!pageLoading">
        <!-- 项目概况 -->
        <Overview
          v-show="!currentAppName && currentAlias == 'villageRent'"
          :detail="villageDetail"
          type="village"
        />
        <!-- 项目信息 -->
        <VillageContent
          v-show="!currentAppName && currentAlias == 'villageInfo'"
          :detail="villageDetail"
        />
        <!-- 应用页面 -->
        <template v-for="appMenu of loadedAppMenu" :key="appMenu.id">
          <!-- todo...  -->
          <!-- <MicroApps
            v-show="appMenu.app == currentAppName"
            pageFrom="village"
            :show="appMenu.app == currentAppName"
            :microName="appMenu.app"
            :loadPage="currentAlias"
          /> -->
          <micro-app-org
            v-show="appMenu.app == currentAppName && appMenu.mounted"
            router-mode="state"
            style="height: 100%"
            :name="appMenu.app + appMenu.arrKey"
            :url=" isProduction ? `${locationUrl}/micro_apps/${appMenu.app}/` : devHttpMap[currentAppName] "
            :default-page="`#${defaultPageData[currentAppName]}`"
            :data="$utils.getAppToChildData({ loadInfo: { villageId } })"
            @mounted="appMenu.mounted = true"
            @datachange="(e) => {handlePageChange(e)}"
          ></micro-app-org>
          <div class="spin-box" v-if="appMenu.app == currentAppName && !appMenu.mounted">
            <a-spin tip="加载中...">
            </a-spin>
          </div>
        </template>
      </template>
    </section>
  </div>
</template>
<script>
import {defineComponent, reactive, toRefs, watch, onMounted, onBeforeUnmount} from "vue";
import request from "../../common/utils/request";
import { FormOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import { BlIcon } from "bl-common-vue3";
// 项目概况
import Overview from "./modules/Overview.vue";
// 项目信息
import VillageContent from "./modules/VillageContent.vue";
// 应用页面
import { useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { message } from "ant-design-vue";
import { MAIN_APP_NAMES } from "../../micro_apps/index";
import microApp from "@micro-zoe/micro-app";

export default defineComponent({
  name: "VillageInfo",
  components: {
    Overview,
    VillageContent,
    BlIcon,
    FormOutlined,
    DeleteOutlined,
  },
  props: {
    // 展示类型 modal弹层展示 page页面内展示
    showType: {
      type: String,
      default: "modal",
    },
    // 项目id
    villageId: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    const ROUTER = useRouter();

    const state = reactive({
      pageLoading: false,
      // 菜单
      menuList: [],
      currentMenu: {},
      // 项目详情
      villageDetail: {},
      // 展示应用页面
      showMicroPages: false,
      currentAppName: "",
      currentAlias: "",
      loadedAppMenu: [],
    });

    /** 编辑项目 */
    const onVillageEdit = () => {
      ROUTER.push({
        name: "projectEdit",
        query: { id: props.villageId },
      });
    };

    /** 删除项目 */
    const onVillageRemove = () => {
      utils.modalConfirm({
        content: "确认删除本项目吗？",
        centered: true,
        okType: "danger",
        onOk: () => {
          request
            .del("/village", "/project/manage", {
              id: props.villageId,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功");
              emit("remove");
            });
        },
      });
    };

    /** 菜单选中 */
    const onMenuSelect = (menu) => {
      const { key } = menu;
      state.currentMenu = state.menuList.find((item) => item.id == key);
      if ( !state.currentMenu.app || MAIN_APP_NAMES.includes(state.currentMenu.app) ) {
        // 主应用内菜单
        state.currentAppName = "";
        state.currentAlias = state.currentMenu.alias;
      } else {
        // 显示子应用内容
        state.currentAppName = state.currentMenu.app;
        state.currentAlias = `${state.currentMenu.alias}?villageId=${props.villageId}`;
        const index = state.loadedAppMenu.findIndex(
          (it) => it.id == state.currentMenu.id
        );
        if (index == -1) {
          state.loadedAppMenu.push(state.currentMenu);
        }
      }
    };

    /** 获取导航菜单 */
    const getMenuList = () => {
      if (state.menuList.length) {
        onMenuSelect({ key: state.menuList[0].id });
        return;
      }
      request
        .get("/village", "/rentControl/menuList", {
          menu_type: "village",
        })
        .then((res) => {
          state.menuList = res.list;
          onMenuSelect({ key: state.menuList[0].id });
        });
    };

    /** 获取项目详情 */
    const getVillageDetail = () => {
      request
        .get("/village", "/project/manage/get", {
          id: props.villageId,
          more: 1,
        })
        .then((res) => {
          state.villageDetail = res.list;
        })
        .finally(() => {
          state.pageLoading = false;
        });
    };

    const handlePageChange = (e) => {
      const data = e?.detail?.data;
      window.microApp.forceDispatch({
        ...data,
      });
    };


    const locationUrl = location.origin;

    const devHttpMap = {
      org: "http://localhost:4001/",
      workVisitor: "http://localhost:4005/",
      workNotice: "http://localhost:4006/",
      workPark: "http://localhost:4007/",
      workEnergy: "http://localhost:4008/",
      workProperty: "http://localhost:4009/",
      workApproval: "http://localhost:4010/",
      workTask: "http://localhost:4011/",
      workSchedule: "http://localhost:4012/",
      workOrder: "http://localhost:4013/",
      workMeetingRoom: "http://localhost:4014/",
      workPatrol: "http://localhost:4015/",
      workCuPage: "http://localhost:4016/",
      workIOT: "http://localhost:4017/",
      workThird: "http://localhost:4018/",
      workForum: "http://localhost:4019/",
      shop: "http://localhost:4020/",
      workAI: "http://localhost:4021/",
      workWiki: "http://localhost:4022/",
      workHr: "http://localhost:4023/",
      workMail: "http://localhost:4024/",
      thirdSichuanPolice: "http://localhost:4025/",
    };

    const defaultPageData = {
      workProperty: "/property/Inventory",
      workOrder: "/order/workOrderDynamics",
      workIOT: "/main/villageIotInfo",
      workEnergy: "/energyConsumption",
      workPark: "/village/ParkList",
    };

    const isProduction = !utils.isEnv();

    onMounted(() => {});

    const UnloadApp = () => {
      state.loadedAppMenu.forEach((item) => {
        microApp.unmountApp(item.app + item.arrKey, { destroy: true, clearAliveState: true })
      });
    };

    const init = () => {
      UnloadApp()
      if (!props.villageId) {
        return;
      }
      state.currentMenu = {}
      state.pageLoading = true;
      getMenuList();
      getVillageDetail();
    };

    onBeforeUnmount(() => {
      UnloadApp();
    });

    watch(
      () => props.villageId,
      () => {
        init();
      }
    );

    init();

    return {
      ...toRefs(state),
      onMenuSelect,
      onVillageEdit,
      onVillageRemove,
      locationUrl,
      devHttpMap,
      defaultPageData,
      isProduction,
      handlePageChange,
      UnloadApp,
    };
  },
});
</script>
<style lang="less" scoped>
.village-info {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    padding: 8px;
    overflow: hidden auto;
    background-color: #f7f7f7;
  }
  .spin-box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
